<template>
	<view
		style=" weight: 100%; overflow: scroll; display: flex; flex-direction: column; align-items: center; padding-top: 40rpx;">
		<view
			style=" weight: 100%; overflow: scroll; display: flex; flex-direction: column; align-items: center; padding-top: 40rpx;">
			<view class="user-info">
				<image class="avatar" :src="userInfo.avatar" v-if="userInfo.avatar && userInfo.avatar !='/static/f.png'"></image>
				<image v-else class="avatar" src="/static/images/f.png"></image>
				<view class="info">
					<view class="name" v-if="userInfo.uid">
						{{userInfo.nickname}}
					</view>
				</view>
			</view>
			
			<view style="width: 100%; padding: 40rpx 40rpx; display: grid; grid-template-columns: 200rpx 1fr 50rpx; align-content: center; background-color: white;">
				<view>当前鱼票</view>
				<view>{{harvest.ticket}}</view>
				<view style="display: flex; justify-content: flex-end;">
					<span class="iconfont">&#xe6bd;</span>	
				</view>
			</view>
			
			<view style="height: 4rpx;"></view>
			
			<view style="width: 100%; padding: 40rpx 40rpx; display: grid; grid-template-columns: 200rpx 1fr 50rpx; align-content: center; background-color: white;">
				<view>选手钓位</view>
				<view>{{harvest.ticket}}</view>
				<view />
			</view>
			
			<view style="height: 4rpx;"></view>
			
			<view style="width: 100%; padding: 40rpx 40rpx; display: grid; grid-template-columns: 200rpx 1fr 50rpx; align-content: center; background-color: white;">
				<view>开始时间</view>
				<view>{{harvest.ticket}}</view>
				<view />
			</view>
			
			<view style="height: 4rpx;"></view>
			
			<view style="width: 100%; padding: 40rpx 40rpx; display: grid; grid-template-columns: 200rpx 1fr 50rpx; align-content: center; background-color: white;">
				<view>结束时间</view>
				<view>{{harvest.ticket}}</view>
				<view />
			</view>
			
			<view style="height: 4rpx;"></view>
			
			<view style="width: 100%; padding: 40rpx 40rpx; display: grid; grid-template-columns: 200rpx 1fr 50rpx; align-content: center; background-color: white;">
				<view>实时渔获</view>
				<view>{{harvest.ticket}}</view>
				<view />
			</view>
			
			<view style="height: 4rpx;"></view>
			
			<view style="width: 100%; padding: 40rpx 40rpx; display: grid; grid-template-columns: 200rpx 1fr 50rpx; align-content: center; background-color: white;">
				<view>实时金币</view>
				<view>{{harvest.ticket}}</view>
				<view />
			</view>
			
			<view
				style="display: flex; justify-content: center; align-items: center; color: orange; font-weight: bold; margin-top:40rpx;"
				v-if="harvest.warning">{{harvest.warning}}</view>
		
			<view style="width: 100%; ">
				<button class='my-btn btMain' @click="onTapBtn" style="margin:20rpx; width: 700rpx;"
					:disabled="btnDisable">{{harvest.btnTitle}}</button>
			</view>
			
		</view>
	</view>
</template>

<script>
	import {
		MyTip
	} from '../../components/ssty/common.js';
	import {
		openFshPage,
		doFshAction,
		changeSeat_isPaid,
		changeSeat_prepairPay
	} from '@/api/fsh.js';
	import {
		getUserInfo
	} from '@/api/user.js';
	const app = getApp();

	import {
		mapGetters
	} from "vuex";


	export default {
		components: {

		},

		data() {
			return {
				isAuto: false,
				isShowAuth: false,
				ypOdId: null,
				ticket: {
					merchantName: "",
					pondName: "",
					partitionName: "",
					seatNo: "",
					day: "",
					timeMode: "",
					allowChangeSeat: 0,
					changeSeatPrice: 0,
					startTime: null,
					endTime: null,
					duratition: null
				},
				prodName: "",
				prodSku: "",
				seatName: "",
				roundName: "",
				startTime: "",
				endTime: "",
				nowRetWeight: "",
				nowRetMoney: "",
				all_scores: null,
				btnTitle: "刷新",
				btnDisable: false,
				countDown: {
					hour: 0,
					minute: 0,
					second: 0,
					start: false
				},
				refreshCountdown: true,

				raceId: 0, // 大于0表示比赛
				warning: '',

				linkTo: `/pages/fsh/fshOrders?filterType=2&pageType=1`,
				userInfo: {},
				
				harvest: {
					btnTitle: "刷新",
				},
			}
		},
		computed: {
			...mapGetters(['isLogin']),

			showTicket() {
				let a = !this.ticket
				let b = !this.ticket.pondName
				return !a && !b
			},
			showCountDown() {
				if (this.countDown) {
					let seconds = this.countDown.hour * 3600 + this.countDown.minute * 60 + this.countDown.second;
					return seconds > 0;
				}
				return false;
			}
		},
		onLoad(options) {
			// if (app.globalData.fshingPageYpOdId) {
			// 	console.log("fishing| onLoad, app.globalData.fshingPageYpOdId=" + app.globalData.fshingPageYpOdId);

			// 	this.ypOdId = app.globalData.fshingPageYpOdId;
			// 	delete app.globalData.fshingPageYpOdId;
			// } else {
			// 	console.log("fishing| onLoad, options=", options);
			// 	this.ypOdId = options.ypOdId;
			// }

			// this.loadFsh(this.ypOdId);
		},

		//点击底部tabbar调用
		onTabItemTap() {
			this.loadFsh();
		},

		onShow() {
			console.log(app.globalData.userInfo)
			if (!app.globalData.userInfo.uid) {
				console.log("get info")
				this.getUserInfo();
			} else {
				console.log("get ok")
				this.userInfo = app.globalData.userInfo
			}
			if (app.globalData.fshingPageYpOdId) {
				console.log("fishing| onShow, app.globalData.fshingPageYpOdId=" + app.globalData.fshingPageYpOdId);
				this.ypOdId = app.globalData.fshingPageYpOdId;
				delete app.globalData.fshingPageYpOdId;
				this.loadFsh(this.ypOdId);
			} else if (this.ypOdId) {
				console.log("fishing| onShow, this.ypOdId=" + this.ypOdId);
				this.loadFsh(this.ypOdId);
			} else {
				console.log("fishing| onShow");
			}
		},
		onHide() {
			console.log("fishing::onHide| ...");
			if (this.tmrid) {
				clearInterval(this.tmrid);
				delete this.tmrid;
			}
		},
		beforeDestroy() {
			console.log("fishing::beforeDestroy| clearInterval ...");
			if (this.tmrid) {
				clearInterval(this.tmrid);
				delete this.tmrid;
			}
		},

		methods: {
			getUserInfo: function() {
				let that = this;
				getUserInfo().then(res => {
					app.globalData.userInfo = res.data,
					that.userInfo = res.data
				});
			},
			// 打开授权
			openAuto() {
				this.isAuto = true;
				this.isShowAuth = true;
				console.log("openAuto, this.isShowAuth=true");
			},
			// 授权回调
			onLoadFun(userInfo) {
				console.log("onLoadFunc, userInfo:", userInfo);
				if (userInfo) { // 得到userInfo，说明登录成功，隐藏授权；否则继续显示授权
					this.isShowAuth = false;
					this.loadFsh();
				}
			},
			// 授权关闭
			authColse: function(e) {
				this.isShowAuth = e
				console.log("authColse, this.isShowAuth=" + this.isShowAuth);
			},
			loadFsh(ypOdId) {
				if (!this.isLogin) {
					console.log("open auth")
					this.openAuto();
					return;
				}
				uni.showLoading({
					title: '正在加载中...'
				});
				openFshPage(ypOdId).then(res => {
					uni.hideLoading();

					this.updFsh(res);

					console.log("loadFsh| openFshPage ok, res=%o, this=%o", res, this);

					if (this.countDown && !this.tmrid) {
						console.log("fishing::loadFsh| setInterval");
						this.tmrid = setInterval(() => this.onTimer(), 5000);
					}

					this.refreshCountdown = false;
					this.$nextTick(() => {
						//console.log("loadFsh| force update countdown");
						//this.$refs.countdown.$forceUpdate();
						this.refreshCountdown = true;
					});
				}).catch(err => {
					uni.hideLoading();
					// console.log("loadFsh| openFshPage(%o) fail:%o", ypOdId, err);
					console.log("loadFsh| openFshPage("+ypOdId+") fail:"+err);
					MyTip(err.msg);
					if (err.msg == '小程序用户未授权') {
						this.openAuto();
					}
				});
			},

			onTimer() {
				console.log("fishing::onTimer");

				var pages = getCurrentPages();
				let curPage = pages[pages.length - 1];
				if (curPage.route != "pages/fsh_main/fishing")
					return;

				openFshPage(this.ypOdId).then(res => {
					this.updFsh(res);

					if (!this.countDown && this.btnTitle.indexOf("...") < 0) {
						if (this.tmrid) {
							console.log("fishing::onTimer| clearInterval");
							clearInterval(this.tmrid);
							delete this.tmrid;
						}
					}
				}).catch(err => {});
			},

			updFsh(res) {
				this.ypOdId = res.entity.odId;
				this.prodName = res.entity.prodName;
				this.prodSku = res.entity.prodSku;
				this.seatName = res.entity.seatName;
				this.roundName = res.entity.roundName;
				this.startTime = res.entity.startTime;
				this.endTime = res.entity.endTime;
				this.nowRetWeight = res.entity.nowRetWeight;
				this.nowRetMoney = res.entity.nowRetMoney;
				this.countDown = res.entity.countDown;
				// this.countDown.hour = res.entity.countDown.hour; // uni-countdown子组件刷新问题：当有多个订单正在垂钓，切换订单后计时器没变；分别赋值不管用。
				// this.countDown.minute = res.entity.countDown.minute;
				// this.countDown.second = res.entity.countDown.second;
				// this.countDown.start = res.entity.countDown.start;
				this.btnDisable = res.entity.btnDisable;
				this.btnTitle = res.entity.btnTitle;
				this.ticket = res.entity.ticket;
				this.raceId = res.entity.raceId;
				this.warning = res.entity.warning;

				this.linkTo = this.raceId ? `/pages/fsh_race/race_detail?raceId=${this.raceId}` : `/pages/fsh/fshOrders?filterType=2&pageType=1`;
				if(res.entity.all_scores){
					this.all_scores = "";
					for(let i in res.entity.all_scores){
						if(i>0){
							let info = res.entity.all_scores[i].split("-")
							this.all_scores += "【第"+i+"场:"+info[0]+"条，"+info[1]+"斤】\n";
						}
					}
				}
				console.log("entity",res.entity)
				console.log("ticket",this.ticket)
				console.log("fishing::updFsh| raceId=" + this.raceId + ", roundName=" + this.roundName);
			},

			onTapBtn() {
				if (this.btnTitle == "查看成绩") {
					uni.navigateTo({
						url: `/pages/fsh_race/race_score?raceId=${this.raceId}`
					})
				} else if (this.btnTitle == "签到" || this.btnTitle == "抽签") {
					uni.navigateTo({
						url: `/pages/fsh_race/draw_lots?raceId=${this.raceId}`
					})
				}
				if (this.lockBtn)
					return;

				uni.showLoading();
				if (this.btnTitle == '选位' || this.btnTitle == '摇号') {
					setTimeout(() => {
						this.lockBtn = false;
					}, 1000);

					if (this.ticket.ypSeatMode == 1) {
						uni.navigateTo({
							url: '/pages/fsh/selectSeat?ypOdId=' + this.ypOdId
						})
					} else {
						uni.navigateTo({
							url: '/pages/fsh/lotterySeat?ypOdId=' + this.ypOdId
						})
					}
					return;
				}

				if (!this.ypOdId) {
					setTimeout(() => {
						this.lockBtn = false;
					}, 1000);
					this.loadFsh();
					return;
				}

				if (this.btnTitle == "结束") {
					setTimeout(() => {
						uni.hideLoading();
						uni.showModal({
							title: '结束',
							content: '请确认您是要结束垂钓吗？',
							success: (res) => {
								setTimeout(() => {
									this.lockBtn = false;
								}, 1000);
								if (res.confirm) {
									doFshAction(this.ypOdId, this.btnTitle).then(res => {
										console.log(
											"fishing::onTapBtn| http doFshAction(%o, %o) res=%o",
											this.ypOdId, this.btnTitle, res);
										uni.hideLoading();

										this.ypOdId = res.entity.odId;
										this.ticket = res.entity.ticket;
										this.startTime = res.entity.startTime;
										this.endTime = res.entity.endTime;
										this.nowRetWeight = res.entity.nowRetWeight;
										this.nowRetMoney = res.entity.nowRetMoney;
										this.countDown = res.entity.countDown;
										this.btnDisable = res.entity.btnDisable;
										this.btnTitle = res.entity.btnTitle;

										if (this.btnTitle.indexOf("...") > 0) {
											if (!this.tmrid) {
												console.log(
													`fishing::doFshAction| action=${this.btnTitle}, setInterval ...`
												);
												this.tmrid = setInterval(() => this.onTimer(),
													1000);
											}
										}
									}).catch(err => {
										console.log(
											"fishing::onTapBtn| http doFshAction(%o, %o) fail=%o",
											this.ypOdId, this.btnTitle, err);
										uni.hideLoading();
										MyTip(err.msg);
									});
								}
							},
							fail: (err) => {
								setTimeout(() => {
									this.lockBtn = false;
								}, 1000);
							}
						});
					}, 2000)

					return;
				}

				doFshAction(this.ypOdId, this.btnTitle).then(res => {
					setTimeout(() => {
						this.lockBtn = false;
					}, 1000);
					console.log("fishing::onTapBtn| http doFshAction(%o, %o) res=%o", this.ypOdId, this.btnTitle,
						res);
					uni.hideLoading();

					this.ypOdId = res.entity.odId;
					this.ticket = res.entity.ticket;
					this.startTime = res.entity.startTime;
					this.endTime = res.entity.endTime;
					this.nowRetWeight = res.entity.nowRetWeight;
					this.nowRetMoney = res.entity.nowRetMoney;
					this.countDown = res.entity.countDown;
					this.btnDisable = res.entity.btnDisable;
					this.btnTitle = res.entity.btnTitle;

					if (this.btnTitle.indexOf("...") > 0) {
						if (!this.tmrid) {
							console.log(`fishing::doFshAction| action=${this.btnTitle}, setInterval ...`);
							this.tmrid = setInterval(() => this.onTimer(), 1000);
						}
					}
				}).catch(err => {
					setTimeout(() => {
						this.lockBtn = false;
					}, 1000);
					console.log("fishing::onTapBtn| http doFshAction(%o, %o) fail=%o", this.ypOdId, this.btnTitle,
						err);
					uni.hideLoading();
					MyTip(err.msg);
				});
			},

			onTapChangeSeat() {
				let that = this;
				//换位最低1元
				if(that.ticket.changeSeatPrice < 1) {
					// uni.navigateTo({
					// 	url: '/pages/fsh/selectSeat?isChangeSeat=1&ypOdId=' + that.ypOdId
					// })
					if (that.ticket.ypSeatMode == 1) {
						uni.navigateTo({
							url: '/pages/fsh/selectSeat?isChangeSeat=1&ypOdId=' + that.ypOdId
						})
					} else {
						uni.navigateTo({
							url: '/pages/fsh/lotterySeat?isChangeSeat=1&ypOdId=' + that.ypOdId
						})
					}
					return;
				}

				changeSeat_isPaid(that.ypOdId).then(res => {
					if (res.entity == 1) {
						// uni.navigateTo({
						// 	url: '/pages/fsh/selectSeat?isChangeSeat=1&ypOdId=' + that.ypOdId
						// })
						if (that.ticket.ypSeatMode == 1) {
							uni.navigateTo({
								url: '/pages/fsh/selectSeat?isChangeSeat=1&ypOdId=' + that.ypOdId
							})
						} else {
							uni.navigateTo({
								url: '/pages/fsh/lotterySeat?isChangeSeat=1&ypOdId=' + that.ypOdId
							})
						}
						return;
					}

					console.log(`单次换位价格：${that.ticket.changeSeatPrice}元`);
					uni.showActionSheet({
						title: `单次换位价格：${that.ticket.changeSeatPrice}元`,
						itemList: [ /*'回鱼支付', '余额支付', */ '微信支付'],
						success: function(res) {
							switch (res.tapIndex) {
								case 0: {
									changeSeat_prepairPay(that.ypOdId).then(res => {
										uni.hideLoading();
										let payParams = res.entity;
										console.log("payParams:", payParams);

										uni.requestPayment({
											timeStamp: payParams.timeStamp,
											nonceStr: payParams.nonceStr,
											package: payParams.package,
											signType: payParams.signType,
											paySign: payParams.paySign,
											success: function(res) {
												if (that.ticket.ypSeatMode == 1) {
													uni.navigateTo({
														url: '/pages/fsh/selectSeat?isChangeSeat=1&ypOdId=' + that.ypOdId
													})
												} else {
													uni.navigateTo({
														url: '/pages/fsh/lotterySeat?isChangeSeat=1&ypOdId=' + that.ypOdId
													})
												}
												// uni.navigateTo({
												// 	url: '/pages/fsh/selectSeat?isChangeSeat=1&ypOdId=' +
												// 		that.ypOdId
												// })
												return that.$util.Tips({
													title: '支付成功',
													icon: 'success'
												});
											},
											fail: function(res) {
												console.log(
													"uni.requestPayment fail: ",
													res);
												return that.$util.Tips({
													title: '支付失败'
												});
											},
											complete: function(res) {
												if (res.errMsg ==
													'requestPayment:cancel')
													return that.$util.Tips({
														title: '取消支付'
													});
											}
										})


									}).catch(err => {
										uni.hideLoading();
										return that.$util.Tips({
											title: err
										})
									});
									break;
								}


							}
						},
						fail: function(res) {
							//console.log(res.errMsg);
						}
					});
				}).catch(err => {
					return that.$util.Tips({
							title: err
					})
				});
			}
		}
	}
</script>

<style lang="scss">
	page {
		height: 100%;
		background-color: #F1F1F1;
	}

	uni-list-item {
		padding: 10rpx 0rpx;
	}

	.lay-sb-c-c {
		display: flex;
		justify-content: space-between;
		align-items: center;
		align-content: center;
	}

	.flex1 {
		flex: 1
	}

	.my-mini-btn {
		height: 50rpx;
		padding-left: 20rpx;
		padding-right: 20rpx;
		border-radius: 10rpx;
		background-color: #905EFF; //#E93323; // var(--view-theme);
		font-size: 25rpx;
		line-height: 50rpx;
		color: #FFFFFF;
	}

	.my-btn {
		height: 86rpx;
		border-radius: 20rpx;
		margin-right: 30rpx;
		margin-left: 30rpx;
		background-color: #905EFF; //#E93323; // var(--view-theme);
		font-size: 30rpx;
		line-height: 86rpx;
		color: #FFFFFF;
	}
	
	.btMain{
	}
	
	.user-info {
		z-index: 20;
		position: relative;
		flex-direction: column;
		display: flex;
		padding: 0 28rpx;
		.avatar {
			width: 250rpx;
			height: 250rpx;
			border-radius: 50%;
		}
	
		.info {
			flex: 1;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			padding: 15rpx 0;
	
			.name {
				width: 250rpx;
				text-align: center;
				align-items: center;
				white-space:nowrap;
				color: #333;
				font-size: 40rpx;
			}
		}
	}
</style>
